import jws from "jws";
import { Service } from "egg";

class EncryptionService extends Service {
  /**
   * 解密token
   * @param token
   */
  decodeToken(token: string) {
    const signature = token.split("Bearer ")[1];
    if (!signature) {
      console.log(token);
    }

    const { payload } = jws.decode(signature);

    switch (typeof payload) {
      case "string": {
        // 控制台token
        const verify = jws.verify(signature, "HS256", this.config.jwt.SECRET);
        if (!verify) {
          throw new Error("token Error");
        }
        return JSON.parse(payload);
      }

      default: {
        throw new Error("typeof sub Error");
      }
    }
  }
}

export default EncryptionService;
